package persistent;

import java.sql.*; 

public class Database implements IPersistent{

	//open connect database
	public Connection open( String hostip, 
										String database,
										String username,
										String password) throws Exception{
		
		Connection connection = null;

        try {
			//load  JDBC Driver
			String driverName = "com.mysql.jdbc.Driver";
			Class.forName(driverName);
            String url = "jdbc:mysql://" + hostip + "/" + database;
            connection = DriverManager.getConnection(url, username, password);

        } catch (Exception e) { 
        	throw new Exception( "Error:"+e.getMessage() );	
        	
        }
        
        return connection;        	
                	
	}
	
	//close connection
	public boolean close( Connection connection ) throws Exception{
	
		boolean result=false;
		
		try {
			connection.close();
			result = true;

		} catch (SQLException e) {
			throw new Exception( "Error:"+e.getMessage() );	
		}
		
		return result;
	}
		

	//execute query
	public ResultSet executeQuery( Connection connection, String query ) throws Exception{
		
		ResultSet result=null;
		
		try{
		
		    if( connection != null ){
		        Statement stm 	=	connection.createStatement( );		
		        result 			=	stm.executeQuery( query );  
		    }
		    
		}catch (Exception e) {
			throw new Exception( "Error:"+e.getMessage() );	
			
		}
		        
	    return result;
	        
	}
	
	//update query
	public int executeUpdate( Connection connection, String query ) throws Exception{
		
		int result=0;
		
		try{
		
		    if( connection != null ){
		        Statement stm 	=	connection.createStatement( );		
		        stm.executeUpdate( query );  
		    }
		    
		    result	=	1;
		    
		}catch (Exception e) {
			throw new Exception( "Error:"+e.getMessage() );	
			
		}
		        
	    return result;
	    
	}
	
}
